// Copyright 2023 ztlcloud.com
// leovs @2023.12.12

package sdk

import (
	_const "gitee.com/leovs/yc-go-sdk/const"
	"gitee.com/leovs/yc-go-sdk/errors"
	"gitee.com/leovs/yc-go-sdk/types"
	"gitee.com/leovs/yc-go-sdk/utils"
	"github.com/gofiber/fiber/v2"
)

type Api struct {
}

// Success 通常成功数据处理
func (e *Api) Success(data ...any) types.IApiResult {
	return e.Json(_const.Success.SetData(utils.Ternary(len(data) == 1, data[0], data)))
}

// Failure 通常错误数据处理
func (e *Api) Failure(data ...any) types.IApiResult {
	return e.Json(_const.Failure.SetData(utils.Ternary(len(data) == 1, data[0], data)))
}

func (e *Api) Json(data ...any) types.IApiResult {
	return e.Result(&types.JsonResult{}, data...)
}

func (e *Api) Jsonp(data ...any) types.IApiResult {
	return e.Result(&types.JsonpResult{}, data...)
}

func (e *Api) Xml(data ...any) types.IApiResult {
	return e.Result(&types.XmlResult{}, data...)
}

func (e *Api) String(data ...any) types.IApiResult {
	return e.Result(&types.StringResult{}, data...)
}

func (e *Api) Null() types.IApiResult {
	return e.Result(&types.NullResult{}, nil)
}

func (e *Api) Redirect() types.IApiResult {
	return e.Result(&types.RedirectResult{}, nil)
}

func (e *Api) HttpCode(code int) types.IApiResult {
	return e.Result(&types.HttpCodeResult{}, code)
}

func (e *Api) View(name string, data fiber.Map) types.IApiResult {
	return e.Result(&types.ViewResult{ViewName: name}, data)
}

func (e *Api) Result(api types.IApiResult, data ...any) types.IApiResult {
	api.SetValue(utils.Ternary(len(data) == 1, data[0], data))
	return api
}

func (e *Api) Errors(err error) types.IApiResult {
	result := &types.JsonResult{}
	if _, ok := err.(*errors.Message); ok {
		result.Value = err
	} else if err != nil {
		result.Value = _const.SystemError.SetMsg(err.Error())
	} else {
		result.Value = _const.SystemError
	}
	return result
}
